package com.sam.java;

import java.util.LinkedList;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * Created by samwang on 2018/4/22.
 */
public class ProducerConsumerWithSemaphore {
    public static void main(String[] args) {
        Storage storage = new Storage();

        new Thread(){
            @Override
            public void run() {
                try {
                    while (storage.optionCount > 0) {
                        storage.produce();
                    }
                    storage.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread(){
            @Override
            public void run() {
                try {
                    while (storage.optionCount > 0) {
                        storage.consume();
                    }
                    storage.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();


    }


    static class Storage {
        LinkedList<Integer> list = new LinkedList<>();
        Random random = new Random();
        Semaphore empty = new Semaphore(10);//空位许可
        Semaphore full = new Semaphore(0);//占位许可
        Semaphore mutex = new Semaphore(1);//读写锁

        int optionCount = 100;//操作完结束

        public void produce() throws InterruptedException {
            empty.acquire();
            mutex.acquire();
            list.add(1);
            System.out.println("produce one , current  " + list.size());
            mutex.release();
            full.release();//占了一个位置
            Thread.sleep(getRandomTime());
            optionCount--;
        }

        public void consume() throws InterruptedException {
            full.acquire();
            mutex.acquire();
            list.remove();
            System.out.println("consume one , current  " + list.size());
            mutex.release();
            empty.release();
            Thread.sleep(getRandomTime() * 2);//slow consume
            optionCount--;
        }

        public void release() {
            mutex.release();
            empty.release();
            full.release();
        }

        public int getRandomTime() {
            return random.nextInt(200);
        }
    }
}
